// 云函数入口文件
const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  const uniIDIns = uniID.createInstance({ context })
  
  let body = event;
  if (event.body != undefined) {
  	body = JSON.parse(event.body)
  }
  
  try {
    // 1. 身份验证
    const { uid } = await uniIDIns.checkToken(body.uniIdToken)
    if (!uid) {
      console.log('身份验证失败')
      return { code: 403, message: '身份验证失败' }
    }

    console.log('身份验证成功，uid:', uid)

    // 2. 查询用户数据
    const db = uniCloud.database()
    const userRes = await db.collection('uni-id-users')
      .doc(uid)
      .field({ test_frequency: true })
      .get()

    console.log('查询到的用户数据:', userRes.data)

    // 3. 处理字段不存在的情况
    if (!userRes.data.length || !userRes.data[0].hasOwnProperty('test_frequency')) {
      console.log('test_frequency 字段不存在，初始化为 0')
      await db.collection('uni-id-users').doc(uid).update({
        test_frequency: 0 // 没有的话设初始值为0
      })
      return { code: 0, needTest: true }
    }

    // 4. 已有字段直接返回
    const testFrequency = userRes.data[0].test_frequency
    const needTest = testFrequency === 0

    console.log(`获取到的 test_frequency: ${testFrequency}, needTest: ${needTest}`)

    return { 
      code: 0, 
      needTest
    }
  } catch (e) {
    console.error('服务器错误:', e)
    return { code: -4, message: '获取失败', error: e }
  }
}
